package com.dzy.chiyan.activity

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.dzy.chiyan.R
import com.dzy.chiyan.adapter.MessageAdapter
import com.dzy.chiyan.data.DBHelper
import com.dzy.chiyan.data.Message
import com.dzy.chiyan.data.MessageDAOImpl
import com.dzy.chiyan.data.UserInfoDaoImpl
// 聊天
class ChatActivity : BaseActivity() {

    private lateinit var messageAdapter: MessageAdapter
    private lateinit var recyclerView: RecyclerView
    private var userID = 0
    private var friendId = 0
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)
        // 初始化用户ID
        userID = intent.getIntExtra("userID", 0)
        friendId = intent.getIntExtra("friendId", 0)

        Log.d("ChatActivity", "userID:$userID friendId:$friendId")
        val dao = UserInfoDaoImpl(DBHelper(this))
        val contactView = findViewById<TextView>(R.id.text_contact_people)
        contactView.text = dao.getUser(friendId)?.nickname
        // 设置联系人名称
        val userName = dao.getUser(userID)?.nickname!!
        val friendName = dao.getUser(friendId)?.nickname!!
        recyclerView = findViewById(R.id.recyclerView_messages)
        recyclerView.layoutManager = LinearLayoutManager(this)
        // 创建适配器实例
        messageAdapter = MessageAdapter(mutableListOf<Message>(), userID, userName, friendName)
        // 加载历史消息
        loadData()
        // 将messageAdapter适配器应用到RecyclerView
        recyclerView.adapter = messageAdapter
    }

    private fun loadData() {
        val dao = MessageDAOImpl(DBHelper(this))
        messageAdapter.reloadData(dao.getMessagesBySenderReceiver(userID, friendId))
        // 滚动到底部
        recyclerView.smoothScrollToPosition(messageAdapter.getItemCount())
    }

    fun onBack(view: View) {
        finish()
    }

    fun onSendMessage(view: View) {
        val messageInputView = findViewById<TextView>(R.id.edit_message)
        // 获取用户输入的消息内容并去除前后空格
        val messageContent = messageInputView.text.toString().trim()
        messageInputView.text = ""
        if (messageContent.isEmpty()) return
        // 如果消息内容不为空，发送
        val sentAt = (System.currentTimeMillis() / 1000).toString()
        val newMessage = Message(0, userID, friendId, messageContent, sentAt)
        val dao = MessageDAOImpl(DBHelper(this)) // 尝试将新消息插入数据库
        if (dao.insertMessage(newMessage)) {
            messageAdapter.addMessage(newMessage)
            // 滚动到底部
            recyclerView.smoothScrollToPosition(messageAdapter.getItemCount() - 1)
        }
    }
}